package com.example.demo.controller;

import com.example.demo.model.Constant;
import com.example.demo.model.User;
import com.example.demo.respository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    //根据id 登录界面   http://localhost:8090/user/login
    @GetMapping("/login")
    public ModelAndView loginEvent( Model model) {
        System.err.println("login====>>");
//        Optional<User> user = userRepository.findById(id);
//        System.err.println("user====>>" + user.get().getName());
//        model.addAttribute("user", user.get());
//        model.addAttribute("title", "查看用户");
        return new ModelAndView("jquery-dl/login", "userModel", model);
    }



    //查词所有用户  http://localhost:8090/user/userlist2?page=1
    @GetMapping("/userlist2")
    public ModelAndView userList2(HttpServletRequest request, Model model) {
        String pagestr = request.getParameter("page");
        System.err.println("userlist2====>>start:" + pagestr);
        if (pagestr == null || pagestr.isEmpty()) {
            pagestr = "1";
        }
        int page_ = Integer.parseInt(pagestr);
        System.err.println("userlist2====>>end:" + page_);

        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page_ - 1, Constant.PAGE_SIZE, sort);//success

        ;//success    分页查询 注意参数的类型，其中size要大于等于1，page则是从0开始算起
        Page<User> userPage = userRepository.findAll(pageable);
        model.addAttribute("userList", userPage);

//        pageable.getPageNumber()
//        getPageSize 是查询到一页的数量
//        getPageNumber 是下标当前第几页
//        getOffset  查询的第一个数位于表的下标位置
        int allpage = userPage.getTotalPages();

        model.addAttribute("title", "用户管理");
        model.addAttribute("page1", true);
        model.addAttribute("page2", allpage >= 2 ? true : false);
        model.addAttribute("page3", allpage >= 3 ? true : false);
        model.addAttribute("page4", allpage >= 4 ? true : false);
        model.addAttribute("pagemore", allpage >= 5 ? true : false);

        model.addAttribute("currentPage", page_);
        model.addAttribute("pages", allpage);
        System.err.println("newsList====>>    page:" + page_ + "        PageSize " + allpage);

        return new ModelAndView("bootstarp/test-list", "userModel", model);
//        return new ModelAndView("user/userlist", "userModel", model);
    }


    //修改用户界面
    @GetMapping(value = "edit2/{id}")
    public ModelAndView editForm2(@PathVariable("id") Long id, Model model) {
        System.err.println("edit2====>>" + id);
        Optional<User> user = userRepository.findById(id);
        model.addAttribute("user", user.get());
        model.addAttribute("title", "编辑用户");

        System.err.println("edit2====>>result:" + user.get().getName());
        return new ModelAndView("bootstarp/user-edit", "userModel", model);
    }  //保存用户


    //根据id删除用户
    @GetMapping(value = "delete2/{id}")
    public ModelAndView delete2(@PathVariable("id") Long id) {
        System.err.println("delete2====>>" + id);   //fail  不存在会报错
        userRepository.deleteById(id);

        return new ModelAndView("redirect:/user/userlist2");//这是action事件，不是html路径
    }


    @PostMapping("{save_update}")
    public ModelAndView saveOrUpdateUser2(User user) {
        System.err.println("saveOrUpdateUser2====>>" + user.getName() + "    " + user.getId());
        user = userRepository.save(user);
//        if(user=user){//判断是否成功
//            success
//        }
        return new ModelAndView("redirect:/user/userlist2");//这是action事件，不是html路径
    }


    //查词所有用户  http://localhost:8090/user/userlist
    @GetMapping("/userlist")
    public ModelAndView userList(Model model) {
        System.err.println("userlist====>>");
        model.addAttribute("userList", userRepository.findAll());
        model.addAttribute("title", "用户管理");

//        return new ModelAndView("bootstarp/test-list", "userModel", model);
        return new ModelAndView("user/userlist", "userModel", model);
    }

    //获取创建表单页面
    @GetMapping("/form2")
    public ModelAndView createForm2(Model model) {
        System.err.println("form====>>" + model.toString());
        model.addAttribute("user", new User(null, null, null, null));
        model.addAttribute("title", "创建用户");
        return new ModelAndView("bootstarp/user-add", "userModel", model);
    }

    //获取创建表单页面
    @GetMapping("/form")
    public ModelAndView createForm(Model model) {
        System.err.println("form====>>" + model.toString());
        model.addAttribute("user", new User(null, null, null, null));
        model.addAttribute("title", "创建用户");
        return new ModelAndView("user/user_edit", "userModel", model);
    }

    //根据id 查询用户
    @GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") Long id, Model model) {
        System.err.println("id====>>" + id);
        Optional<User> user = userRepository.findById(id);
        System.err.println("user====>>" + user.get().getName());
        model.addAttribute("user", user.get());
        model.addAttribute("title", "查看用户");
        return new ModelAndView("user/user_detail", "userModel", model);
    }


    //保存用户
    @PostMapping
    public ModelAndView saveOrUpdateUser(User user) {
        System.err.println("saveOrUpdateUser====>>" + user.getName() + "    " + user.getId());
        user = userRepository.save(user);
        return new ModelAndView("redirect:/user/userlist");//这是action事件，不是html路径
    }

    //根据id删除用户
    @GetMapping(value = "delete/{id}")
    public ModelAndView delete(@PathVariable("id") Long id) {
        System.err.println("delete====>>" + id);   //fail  不存在会报错
        userRepository.deleteById(id);

        return new ModelAndView("redirect:/user/userlist");//这是action事件，不是html路径
    }

    //修改用户界面
    @GetMapping(value = "edit/{id}")
    public ModelAndView editForm(@PathVariable("id") Long id, Model model) {
        System.err.println("edit====>>" + id);
        Optional<User> user = userRepository.findById(id);
        model.addAttribute("user", user.get());
        model.addAttribute("title", "编辑用户");
        return new ModelAndView("user/user_edit", "userModel", model);
    }
}